package com.ruoyi.io;

import java.io.*;

public class ByteArrayInputStreamExample {
    public static void main(String[] args) {
        byte[] bytes = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33};
        // 创建字节输入流对象
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

        try {
            byte[] buffer = new byte[1024];
            int len;
            // 使用 while 循环读取字节数组中的内容，每次最多读取 1024 个字节
            while ((len = bais.read(buffer)) != -1) {
                // 将读取的字节转换为字符串，并输出到控制台
                String content = new String(buffer, 0, len, "UTF-8");
                System.out.println(content);
            }
        } catch (IOException e) {
            System.out.println("Error reading byte array: " + e.getMessage());
        } finally {
            // 关闭输入流
            try {
                if (bais != null) {
                    bais.close();
                }
            } catch (IOException e) {
                System.out.println("Error closing byte array input stream: " + e.getMessage());
            }
        }
    }
}
